package com.video.information.ui.home.video

import android.annotation.SuppressLint
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.dueeeke.videocontroller.StandardVideoController
import com.dueeeke.videocontroller.component.*
import com.dueeeke.videoplayer.player.AbstractPlayer
import com.dueeeke.videoplayer.player.VideoView
import com.dueeeke.videoplayer.player.VideoViewManager
import com.google.gson.Gson
import com.video.information.Const
import com.video.information.R
import com.video.information.data.model.Video
import com.video.information.ui.common.holder.ItemVideoHolder
import com.video.information.ui.common.listener.OnItemVideoClickListener
import com.video.information.ui.common.ui.BaseFragment
import com.video.information.util.ViewUtils
import kotlinx.android.synthetic.main.fragment_video.*
import java.util.ArrayList

class VideoFragment(private val categoryId: Int) : BaseFragment(), OnItemVideoClickListener {

    companion object {
        fun newInstance(categoryId: Int) = VideoFragment(categoryId)
    }

    private var videoAdapter: VideoAdapter? = null

    private var videoDataList: List<Video.RECORDSBean>? = null

    private var showVideoList = ArrayList<Video.RECORDSBean>()

    private var linearLayoutManager: LinearLayoutManager? = null

    /**
     * 当前播放的item
     */
    private var mCurPos = -1

    /**
     * 上次播放的位置，用于页面切回来之后恢复播放
     */
    private var mLastPos = mCurPos

    private var mVideoView: VideoView<*>? = null
    private var mController: StandardVideoController? = null
    private var mErrorView: ErrorView? = null
    private var mCompleteView: CompleteView? = null
    private var mTitleView: TitleView? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return onCreateView(inflater.inflate(R.layout.fragment_video, container, false))
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initVideoView()
        linearLayoutManager = LinearLayoutManager(getActivity())
        linearLayoutManager?.orientation = LinearLayoutManager.VERTICAL
        recyclerView.layoutManager = linearLayoutManager
        videoAdapter = VideoAdapter()
        videoAdapter?.onItemVideoClickListener = this
        recyclerView.adapter = videoAdapter

        recyclerView.addOnChildAttachStateChangeListener(object :
            RecyclerView.OnChildAttachStateChangeListener {
            override fun onChildViewAttachedToWindow(view: View) {

            }

            override fun onChildViewDetachedFromWindow(view: View) {
                val frameLayout: FrameLayout = view.findViewById(R.id.player_container)
                val v = frameLayout.getChildAt(0)
                if (v != null && v == mVideoView && !mVideoView!!.isFullScreen) {
                    releaseVideoView()
                }
            }
        })
        // 下拉刷新
        smartRefreshLayout.setOnRefreshListener {
            showVideoList.clear()
            notifyVideoData(true)
        }

        // 上拉更新
        smartRefreshLayout.setOnLoadMoreListener {
            notifyVideoData(false)
        }

        videoDataList = Gson().fromJson(Video.mVideos, Video::class.java).RECORDS

        notifyVideoData(true)
    }

    /**
     * 更新或刷新recyclerView
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun notifyVideoData(isRefresh: Boolean) {
        if (isRefresh) {
            smartRefreshLayout.finishRefresh(true)
        } else {
            smartRefreshLayout.finishLoadMore(true)
            return
        }
        videoDataList?.forEach {
            if (it.category_id == categoryId) {
                showVideoList.add(it)
            }
        }
        videoAdapter?.videoData = showVideoList
        videoAdapter?.notifyDataSetChanged()
    }

    /**
     * PrepareView被点击
     */
    override fun onItemChildClick(position: Int) {
        startPlay(position)
    }

    /**
     * 初始化视频控件
     */
    private fun initVideoView() {
        mVideoView = VideoView<AbstractPlayer>(requireContext())
        mVideoView?.setOnStateChangeListener(object : VideoView.SimpleOnStateChangeListener() {
            override fun onPlayStateChanged(playState: Int) {
                if (playState == VideoView.STATE_IDLE) {
                    ViewUtils.removeViewFormParent(mVideoView)
                    mLastPos = mCurPos
                    mCurPos = -1
                }
            }
        })
        mController = StandardVideoController(requireActivity())
        mErrorView = ErrorView(getActivity())
        mController!!.addControlComponent(mErrorView)
        mCompleteView = CompleteView(requireActivity())
        mController!!.addControlComponent(mCompleteView)
        mTitleView = TitleView(requireActivity())
        mController!!.addControlComponent(mTitleView)
        mController!!.addControlComponent(VodControlView(requireActivity()))
        mController!!.addControlComponent(GestureView(requireActivity()))
        mController!!.setEnableOrientation(true)
        mVideoView?.setVideoController(mController)
    }

    /**
     * 播放视频
     * @param position 列表位置
     */
    private fun startPlay(position: Int) {
        if (mCurPos == position) return
        if (mCurPos != -1) {
            releaseVideoView()
        }
        val recordsBean = showVideoList[position]
        mVideoView?.setUrl(recordsBean.playUrl)
        mTitleView?.setTitle(recordsBean.vtitle)
        val itemView = linearLayoutManager?.findViewByPosition(position) ?: return
        val viewHolder = itemView.tag as ItemVideoHolder
        // 把列表中预置的PrepareView添加到控制器中，注意isPrivate此处只能为true。
        mController?.addControlComponent(viewHolder.mPrepareView, true)
        ViewUtils.removeViewFormParent(mVideoView)
        viewHolder.mPlayerContainer.addView(mVideoView, 0)
        // 播放之前将VideoView添加到VideoViewManager以便在别的页面也能操作它
        VideoViewManager.instance().add(mVideoView, Const.SHOW_VIDEO)
        mVideoView?.start()
        mCurPos = position
    }

    /**
     * 释放播放让播放停止
     */
    private fun releaseVideoView() {
        mVideoView?.release()
        if (mVideoView!!.isFullScreen) {
            mVideoView?.stopFullScreen()
        }
        if (requireActivity().requestedOrientation != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            requireActivity().requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        }
        mCurPos = -1
    }

    /**
     * 由于onResume必须调用super。故增加此方法，
     * 子类将会重写此方法，改变onResume的逻辑
     */
    private fun resume() {
        if (mLastPos == -1) return
        //恢复上次播放的位置
        startPlay(mLastPos)
    }

    override fun onResume() {
        super.onResume()
        resume()
    }

    /**
     * 由于onPause必须调用super。故增加此方法，
     * 子类将会重写此方法，改变onPause的逻辑
     */
    private fun pause() {
        releaseVideoView()
    }

    override fun onPause() {
        super.onPause()
        pause()
    }

}